#!/usr/bin/env bash
#
# Automatically sets the wrappers for textmate's use
# Based on article posted: http://www.christopherirish.com/2010/06/28/how-to-setup-textmate-to-use-rvm/
# Set up the TM_RUBY shell variable as described and remove the Builder as described and restart TextMate
#
# Make this script executable and you should be good to go! TextMate will stay in sync with rvm, which
# generally means the last project folder you switched into from terminal shell.
#

function set_textmate_wrapper()
{
  typeset __current_ruby __textmate_ruby
  __current_ruby=${RUBY_VERSION:-${GEM_HOME##*/}}

  if
    __textmate_ruby="$( \which textmate_ruby 2>/dev/null )" &&
    [[ -n "${__textmate_ruby:-}" ]]
  then
    __textmate_ruby="$( readlink "${__textmate_ruby:-}" )"
    __textmate_ruby="${__textmate_ruby%/ruby}"
    __textmate_ruby="${__textmate_ruby%/bin}"
  fi
  if
    [[ -z "${__textmate_ruby}" || "${__textmate_ruby}" != "${__current_ruby:-}" ]]
  then
    rvm wrapper ${RUBY_VERSION:-${GEM_HOME##*/}} textmate
  fi
}

if
  [[ $TM_WRAPPING != "1" ]]
then
  export TM_WRAPPING="1"
  set_textmate_wrapper
  unset TM_WRAPPING
fi
